import weatherAcquisition
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# 将其实例化，创建app对象
app = FastAPI()

# 跨域问题的解决
# 配置允许域名
origins = ["*"]
# 配置允许域名列表、允许方法、请求头、cookie等
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"])


@app.get("/")
def index():
    return {"code": "200", "msg": "欢迎查询天气！"}


@app.get("/weather/q")
def queryWeather(cityName):
    html = weatherAcquisition.obtainHtml(cityName=cityName)
    weatherData = weatherAcquisition.queryWeather(html=html)
    if weatherData != "查不到此地方！":
        return {"code": "200", "data": weatherData, "msg": "查询成功！"}
    else:
        return {"code": "500", "msg": "查询失败"}


@app.get("/livingIndex/q")
def queryLivingIndex(cityName):
    html = weatherAcquisition.obtainHtml(cityName=cityName)
    livingIndex = weatherAcquisition.queryLivingIndex(html=html)
    if livingIndex != "查不到此地方！":
        return {"code": "200", "data": livingIndex, "msg": "查询成功！"}
    else:
        return {"code": "500", "msg": "查询失败"}


# uvicorn.run(app, host="192.168.1.185")
uvicorn.run(app)
